<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class DistanceCalculations
 * Desc  距离计算控制器
 * Create on 2024/11/11 15:03
 * Create by wangyafang
 */

namespace app\api\controller\wddj\trailer;



use app\api\model\wddj\Config;
use app\api\model\wddj\User;
use app\common\controller\Api;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class DistanceCalculations extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['submit'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\trailer\DistanceCalculations();
        $wechat_id = User::getWechatId($this->auth->id);
        $driverObj = (new \app\api\model\wddj\trailer\Driver())->where('wechat_id',$wechat_id)->find();
        if (!$driverObj) {
            $this->error('不是司机，没有权限,请先认证');
        }
    }

    /**
     * Desc 定时提交经纬度
     * Create on 2024/11/11 15:04
     * Create by wangyafang
     */
    public function submit()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->param();
        $result = $this->validate($param,'app\api\validate\wddj\trailer\DistanceCalculations');
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->error($result);
        }


        $data = $_POST['data'];


        $orderObj = (new \app\api\model\wddj\trailer\Order())->get($param['order_id']);

        $map_data = json_decode($data,true);


        $driverObj = (new \app\api\model\wddj\trailer\Driver())->get($orderObj['driver_id']);
        if ($orderObj['state'] == 'in_progress' && !empty($map_data)) {
            $insert_data = array();
            $actual_meter = $orderObj->actual_meter;
            $actual_duration = $orderObj->actual_duration;
            $distanceCalculationsObj = $this->model->where('order_id',$param['order_id'])->order('id desc')->field('lat,lng')->find();
            if ($distanceCalculationsObj) {
                $first = $distanceCalculationsObj->toArray();
                array_unshift($map_data, $first);
            }
            $key = (new Config())->where('id',1)->value('tencent_map_web_service_key');
            $count = count($map_data);
            for ($i = 1; $i < $count; $i++) {
                $from = $map_data[$i-1]['lat'].','.$map_data[$i-1]['lng'];
                $to = $map_data[$i]['lat'].','.$map_data[$i]['lng'];
                $url = "https://apis.map.qq.com/ws/distance/v1/matrix?mode=driving&from=$from&to=$to&key=$key";
                $result = wddj_curl_get_https($url);
                $mapResult = json_decode($result,true);
                if ($mapResult['status'] != 0) {
                    $this->error('腾讯地图错误提示：'.$mapResult['message']);
                } else {
                    $meter = $mapResult['result']['rows'][0]['elements'][0]['distance'];
                    $duration = $mapResult['result']['rows'][0]['elements'][0]['duration'];
                    $actual_meter = bcadd($actual_meter,$meter,2);
                    $actual_duration = bcadd($actual_duration,$duration,0);
                    $insert_data[] = array(
                        'lng'=>$map_data[$i]['lng'],
                        'lat'=>$map_data[$i]['lat'],
                        'order_id'=>$param['order_id'],
                        'meter'=>$meter,
                        'duration'=>$duration
                    );
                }
                unset($from);
                unset($to);
            }

            Db::startTrans();
            try {
                $this->model->saveAll($insert_data);
                $orderObj->actual_meter = $actual_meter;
                $orderObj->actual_duration = $actual_duration;
                $orderObj->save();
                $driverObj->driver_lng = $map_data[$count-1]['lng'];
                $driverObj->driver_lat = $map_data[$count-1]['lat'];
                $driverObj->save();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


        }

        $this->success('请求成功');
    }





}



 